package org.zebra.captcha;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zebra.cache.ext.ratelimiter.LimitType;
import org.zebra.cache.ext.ratelimiter.RateLimiter;
import org.zebra.captcha.mail.MailCaptchaHandler;
import org.zebra.captcha.picture.PictureCaptchaHandler;
import org.zebra.captcha.picture.PictureCaptchaVo;
import org.zebra.captcha.sms.SmsCaptchaHandler;
import org.zebra.common.core.R;

import javax.validation.constraints.NotBlank;

/**
 * 验证码操作处理
 *
 * @author zhanghongbin
 */
@Slf4j
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private PictureCaptchaHandler pictureCaptchaHandler;

    @Autowired(required = false)
    private MailCaptchaHandler mailCaptchaHandler;

    @Autowired
    private SmsCaptchaHandler smsCaptchaHandler;

    /**
     * 短信验证码
     *
     * @param phoneNumber 用户手机号
     */
    @RateLimiter(key = "#phoneNumber", time = 60, count = 1)
    @Validated
    @GetMapping("/sms/code")
    public void smsCode(@NotBlank(message = "手机号不能为空") String phoneNumber) {
        boolean flag = smsCaptchaHandler.build(phoneNumber);
        if (!flag) {
            R.failed("短信验证码发送异常,请稍后再试!");
        }
    }

    /**
     * 邮箱验证码
     *
     * @param email 邮箱
     */
    @Validated
    @RateLimiter(key = "#email", time = 60, count = 1)
    @GetMapping("/email/code")
    public void getEmailCode(@NotBlank(message = "邮箱不能为空") String email) {
        if (mailCaptchaHandler != null) {
            boolean flag = mailCaptchaHandler.build(email.trim());
            if (!flag) {
                R.failed("邮箱验证码发送异常,请稍后再试!");
            }
        } else {
            R.failed("当前系统没有开启邮箱功能!");
        }
    }

    /**
     * 图片验证码
     *
     * @return 对象
     */
    @RateLimiter(time = 60, count = 10, limitType = LimitType.IP, msg = "验证码访问频繁，请稍后再试")
    @GetMapping("/picture/code")
    public PictureCaptchaVo getPictureCode() {
        String uuid = IdUtil.simpleUUID();
        return pictureCaptchaHandler.build(uuid);
    }
}
